﻿using CommonTool;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace AutoMachine
{
    public class TCPClientScan
    {
        #region 窗体实例化
        /// <summary>
        /// 窗体对象实例化
        /// </summary>
        //private static TCPClientScan _instance;
        //internal static TCPClientScan Instance
        //{
        //    get
        //    {
        //        if (_instance == null)
        //            _instance = new TCPClientScan();
        //        return _instance;
        //    }
        //}
        #endregion
        public TCPClientScan(string strIp, string strPort)
        {
            this.m_strPort = strPort;
            this.m_strIp = strIp;
        }


        /// <summary>
        ///通讯用Socket 
        /// </summary>
        public  Socket socketclient = null;
        string m_strIp = "192.168.1.99", m_strPort = "1436";
        public string m_strReceive;
        /// <summary>
        /// 委托函数
        /// </summary>
        /// <param name="logListBox"></param>
        /// <param name="strLog"></param>
        public delegate void DataReceivedHandler(string strReive);

        /// <summary>
        /// 事件
        /// </summary>
        public event DataReceivedHandler DataReceivedEvent;

        /// <summary>
        /// 接收消息的线程
        /// </summary>
        public Thread th_receive = null;

        //运行标志位
        public bool IsRunning = false;

        /// <summary>
        /// 信息显示
        /// </summary>
        /// <param name="message"></param>
        public void ShowMsg(string str)
        {
            if (str == "")
            {
                return;
            }
            //txtMsg.AppendText(str + "\r\n");
            m_strReceive = str;
            DataReceivedEvent(m_strReceive);
            LogView.GetInstance().ShowLogSave(LogView.LogType.Oper, "FromCCD==>" + m_strReceive);
        }




        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="msg"></param>
        internal void Send(string msg)
        {
            try
            {
                byte[] buffer = Encoding.ASCII.GetBytes(msg);
                socketclient.Send(buffer);
                LogView.GetInstance().ShowLogSave(LogView.LogType.Oper, "ToCCD==>" + msg);//保存Log
                //ShowMsg("->: " + tbx_sendMessage.Text.Trim());
            }
            catch (Exception ex)
            {
                //LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                MessageBox.Show(ex.Message);
            }
        }

        object LockSend = new object();
        Mutex mytex = new Mutex();
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="msg"></param>
        internal void Send(byte[] buffer)
        {
            //lock (LockSend)
            //{
            mytex.WaitOne();
                try
                {

                    socketclient.Send(buffer);
                    LogView.GetInstance().ShowLogSave(LogView.LogType.Oper, "ToCCD==>" + buffer.ToString());//保存Log
                                                                                                            //ShowMsg("->: " + tbx_sendMessage.Text.Trim());
                }
                catch (Exception ex)
                {
                    //LogView.GetInstance().ShowLogSave(LogView.LogType.Error, ex.Message);//保存Log
                    //MessageBox.Show(ex.Message);

                    Connect();
                }
                Thread.Sleep(10);
            mytex.ReleaseMutex(); 
            //}

        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        public bool Connect()
        {
            
            try
            {
            Again:
                Thread.Sleep(500);
                IPAddress address = IPAddress.Parse(m_strIp);

                IPEndPoint Ipe = new IPEndPoint(address, int.Parse(m_strPort));

                socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    socketclient.Connect(Ipe);//连接

                }
                catch
                {

                    //if (MessageBox.Show("连接失败，可能是第三方通讯设备未正常运行，请在第三方通讯设备正常运行后点击确定，或直接点击取消放弃连接。", "提示：", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    //{
                        goto Again;
                    //}
                }
                if (socketclient.Connected)//已连接上
                {
                    IsRunning = true;
                    if (th_receive == null)
                    {
                        th_receive = new Thread(ReceiveMsg);
                        th_receive.IsBackground = true;//后台线程
                        th_receive.Start();

                    }
                    else if(!th_receive.IsAlive)
                    {
                        th_receive.Start();
                    }

                    return true;
                    //  btn_connect.Text = "断开";
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        public void Close()
        {
            IsRunning = false;
            if (socketclient != null)
            {
                if (socketclient.Connected)
                {
                    socketclient.Disconnect(false);
                }
            }
            socketclient.Close();
            if (th_receive != null)
            {
                if (th_receive.IsAlive)
                {
                    th_receive.Abort();
                }

            }


        }
        /// <summary>
        /// 接收消息
        /// </summary>
        private void ReceiveMsg()
        {
            try
            {
                //定义一个2M缓冲区
                byte[] buffer = new byte[1024 * 1024*2];
                while (IsRunning)
                {
                    Thread.Sleep(10);
                    int length = 0;
                    try
                    {
                        length = socketclient.Receive(buffer);
                    }
                    catch (Exception ex)
                    {
                        IsRunning = false;
                        //MessageBox.Show(ex.Message+ex.StackTrace+ex.Source+ socketclient.RemoteEndPoint.ToString());
                    }
                    string result = Encoding.ASCII.GetString(buffer, 0, length);
                    if (length > 0)
                    {
                        ShowMsg(result);
                    }
                    else
                    {
                        if (socketclient != null)
                        {
                            IsRunning = false;
                            try
                            {
                                socketclient.Dispose();
                                socketclient.Disconnect(true);
                                socketclient.Close();//关闭
                            }
                            catch (Exception ex) {
                                //IsRunning = false;
                                //MessageBox.Show(ex.Message + ex.StackTrace + ex.Source + socketclient.RemoteEndPoint.ToString()); 
                            }
                        }
                        th_receive = null;
                        socketclient = null;
                        
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace + ex.Source + socketclient.RemoteEndPoint.ToString());
            }


        }
    }
}
